
function startMoveAnimal(single = false) {
    if (!hasAnimals() && !hasStables()) {
        alert('当前没有任何动物或畜棚可供移动。');
        return;
    }
    const action = single ? '移动1只动物或畜棚' : '移动动物或畜棚';
    if (!confirm(`确定要${action}吗？`)) {
        return;
    }
    window.actionData.status = single ? "moveSingleAnimal" : "moveAnimal";

    // 显示移动动物的提示视图
    updateAdditionalView();

    updateFarmCellForMovingAnimal();
}

function updateFarmCellForMovingAnimal() {
    if (window.actionData.status == "moveAnimal" || window.actionData.status == "moveSingleAnimal" || window.actionData.status == "removeAnimal") {
        let selectedAnimal = window.actionData.moveAnimal;
        if (selectedAnimal == null) {
            // 高亮所有有动物的格子
            window.myData.farmCells.forEach(column => {
                column.forEach(cell => {
                    if (cell.sheep > 0 || cell.pig > 0 || cell.cattle > 0 || cell.building === "stable") {
                        getCellNode(cell.x, cell.y).addClass('moveable');
                    }
                });
            });
        } else {
            // 移除可移动高亮
            $('.farm-cell').removeClass('moveable');
            // 仅高亮当前选中的格子
            getCellNode(selectedAnimal.x, selectedAnimal.y).addClass('target');
        }
    } else {
        // 移除高亮
        $('.farm-cell').removeClass('moveable target');
    }
}

function hasAnimals() {
    return window.myData.farmCells.some(column => 
        column.some(cell => cell.sheep > 0 || cell.pig > 0 || cell.cattle > 0)
    );
}

function hasStables() {
    return window.myData.farmCells.some(column => 
        column.some(cell => cell.building === "stable")
    );
}

function updateAnimalButtonsVisibility() {
    const hasAnyAnimals = hasAnimals();
    const statusIsEmpty = window.actionData.status === null;
    document.getElementById("move-animal-btn").style.display = hasAnyAnimals && statusIsEmpty ? "inline-block" : "none";
    document.getElementById("move-single-animal-btn").style.display = hasAnyAnimals && statusIsEmpty ? "inline-block" : "none";
    document.getElementById("remove-animal-btn").style.display = hasAnyAnimals && statusIsEmpty ? "inline-block" : "none";
}

function moveAnimal(targetX, targetY, single = false) {
    const { x, y, type } = window.actionData.moveAnimal;

    // 检查目标坐标是否与源坐标相同
    if (x === targetX && y === targetY) {
        alert('目标位置不可以与当前位置一致');
        return;
    }

    const sourceCell = window.myData.farmCells[x][y];
    const targetCell = window.myData.farmCells[targetX][targetY];

    if (type === "stable") {
        if (targetCell.building != null) {
            alert('目标位置已有建筑，无法移动畜棚');
            return;
        }
        targetCell.building = "stable";
        sourceCell.building = null;
    } else {
        // 移动动物到目标格子
        if (single) {
            if (sourceCell[type] > 0) {
                targetCell[type] += 1;
                sourceCell[type] -= 1;
            }
        } else {
            targetCell[type] += sourceCell[type];
            sourceCell[type] = 0;
        }
    }

    // 更新农场和状态
    updateFarm();
    endMoveAnimal();
}

function endMoveAnimal() {
    window.actionData.moveAnimal = null;
    endAction();
    updateFarmCellForMovingAnimal();
}

function showAnimalSelectionDialog(cell, callback) {
    const animals = ['sheep', 'pig', 'cattle'];
    const animalNames = { sheep: '羊', pig: '猪', cattle: '牛' };

    let availableAnimals = animals.filter(animal => cell[animal] > 0).map(animal => ({
        value: animal,
        label: `${animalNames[animal]} (${cell[animal]})`
    }));

    // 如果是移动动物或畜棚状态，并且有畜棚，添加畜棚选项
    if ((window.actionData.status == "moveAnimal" || window.actionData.status == "moveSingleAnimal") && cell.building === "stable") {
        availableAnimals.push({ value: 'stable', label: '畜棚' });
    }

    // 如果只有一种动物，直接选中该动物
    if (availableAnimals.length === 1 && window.actionData.status != "removeAnimal") { // 删除动物时依然会弹窗，以便用户确认。
        callback(availableAnimals[0].value);
        return;
    }

    var actionText = '移动';
    if (window.actionData.status == "removeAnimal") {
        actionText = '删除';
    }

    showSelectionDialog(`选择要${actionText}的动物`, availableAnimals, callback);
}

/// 删除动物
function startRemoveAnimal() {
    if (!hasAnimals()) {
        alert('当前没有任何动物可以删除。');
        return;
    }
    if (!confirm('确定要删除动物吗？')) {
        return;
    }
    window.actionData.status = "removeAnimal";
    updateAdditionalView();
    updateFarmCellForMovingAnimal();
}

function removeAnimal(x, y) {
    const cell = window.myData.farmCells[x][y];
    if (cell.sheep > 0 || cell.pig > 0 || cell.cattle > 0) {
        showAnimalSelectionDialog(cell, function(selectedAnimal) {
            if (cell[selectedAnimal] > 0) {
                cell[selectedAnimal] -= 1;
            }
            updateFarm();
            endRemoveAnimal();
        });
    }
}

function endRemoveAnimal() {
    endAction();
    updateFarmCellForMovingAnimal();
}